/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { log, warn } from 'cc';
import { DEBUG_CORE } from './base';

const TAG = 'lcc/core/reference.ts';

/**
 * @zh
 * 引用类
 */
class Reference {
    /**
     * @zh
     * 静态对象
     */
    private static _instance: Reference = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (Reference._instance === null) {
            Reference._instance = new Reference();
        }
        return Reference._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 引用映射表
     */
    private _referenceMap: { [key: string]: any } = Object.create(null);

    /**
     * @zh
     * 获得指定引用
     *
     * @param key 键
     */
    get<T = any>(key: string) {
        return this._referenceMap[key] as T;
    }

    /**
     * @zh
     * 设置指定引用
     *
     * @param key 键
     * @param value 值
     */
    set(key: string, value: any) {
        if (this._referenceMap[key]) {
            warn(TAG, `key ${key} conflict`);
        }
        DEBUG_CORE && log(TAG, `set ${key} => ${value}`);
        this._referenceMap[key] = value;
    }

    /**
     * @zh
     * 移除指定引用
     *
     * @param key 键
     */
    remove(key: string) {
        DEBUG_CORE && log(TAG, `remove ${key}`);
        delete this._referenceMap[key];
    }
}

/**
 * @zh
 * 引用对象
 */
export const reference = Reference.instance;

/**
 * @zh
 * 装饰器 - 设置引用
 */
export function ref(key: string) {
    return function (target: Function) {
        reference.set(key, target);
    };
}
